package com.incms.web.modules.system.service;

import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.collections.CollectionUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.google.common.collect.Maps;
import com.incms.web.common.util.Page;
import com.incms.web.modules.system.dao.SysMenuDao;
import com.incms.web.modules.system.dao.SysRoleDao;
import com.incms.web.modules.system.entity.SysMenu;
import com.incms.web.modules.system.entity.SysRole;

/**
 * 项目名称：inCms    
 * 类名称：SysRoleService    
 * 类描述：    
 * 创建人：liujunqing    
 * 创建时间：2015年10月23日  
 * @version 1.0    
 *
 */
@Service("sysRoleService")
public class SysRoleService {
	
	@Resource(name = "sysRoleDao")
	private SysRoleDao sysRoleDao;
	
	@Resource(name = "sysMenuDao")
	private SysMenuDao sysMenuDao;
	
	/**
	 * 保存角色
	 */
	@Transactional
	public Long save(SysRole sysRole){
		Long roleId = sysRoleDao.save("SysRoleMapper.saveSysRole", sysRole);
		List<SysMenu> sysMenus = sysRole.getSysMenus();
		if(CollectionUtils.isNotEmpty(sysMenus)){
			for(SysMenu m : sysMenus){
				Map<String,Long> map =Maps.newHashMap();
				map.put("roleId", roleId);
				map.put("menuId", m.getMenuId());
				sysMenuDao.save("SysRoleMapper.saveSysRoleMenu", map);
			}
		}
		return roleId;
	}
	
	/**
	 *更新角色 
	 */
	@Transactional
	public Long update(SysRole sysRole){
		Long updateId = sysRoleDao.update("SysRoleMapper.updateSysRole", sysRole);
		//先删除中间表然后删除
		Long flag = this.deleteSysRoleMenu(sysRole.getRoleId());
		if(flag > 0){
			this.save(sysRole);
		}
		return updateId;
	}
	
	/**
	 *删除角色 
	 */
	@Transactional
	public Long delete(Long roleId){
		return sysRoleDao.delete("SysRoleMapper.deleteSysRole", roleId);
	}
	
	/**
	 *删除中间表 
	 */
	@Transactional
	public Long deleteSysRoleMenu(Long roleId){
		return sysRoleDao.delete("SysRoleMapper.deleteSysRoleMenu", roleId);
	}
	
	/**
	 *根据条件查询 
	 */
	@Transactional(readOnly=true)
	public List<SysRole> findList(SysRole sysRole){
		return sysRoleDao.findList("SysRoleMapper.findList",sysRole);
	}
	
	@Transactional(readOnly=true)
	public Page<SysRole> queryRolePage(Page<SysRole> page,SysRole sysRole){
		return sysRoleDao.queryForListPage("SysRoleMapper.querySysRolePage", sysRole, page);
	}
	
	@Transactional(readOnly=true)
	public SysRole findRoleId(Long sysRoleId){
		return sysRoleDao.findOne("SysRoleMapper.findRoleId", sysRoleId);
	}

	@Transactional(readOnly=true)
	public Boolean findCheckRoleName(String roleName) {
		Integer count = (Integer)sysRoleDao.findOne("SysRoleMapper.checkRoleName", roleName);
		return count != null && count > 0 ? false : true;
	}
	
	
}
